﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;

using FRC_Turtle.ViewModels;

namespace FRC_Turtle
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        FRCTurtleViewModel vm;

        public MainWindow()
        {
            InitializeComponent();
            vm = this.DataContext as FRCTurtleViewModel;
        }

        private void Image_MouseUp_1(object sender, MouseButtonEventArgs e)
        {
            double width = img.ActualWidth;
            double height = img.ActualHeight;

            var point = e.GetPosition(img);

            double percentX = point.X / width;
            double percentY = point.Y / height;

            double actualX = percentX * FRCTurtleViewModel.FieldWidth;
            double actualY = percentY * FRCTurtleViewModel.FieldHeight;

            if (e.ChangedButton == MouseButton.Left)
            {
                vm.Points.Add(new TGPoint(actualX, actualY));
            }
            else if (e.ChangedButton == MouseButton.Right)
            {
                TGPoint p = vm.Points.Last();
                p.ShotCount++;


                double head = (Math.Atan2(actualY - p.Y, actualX - p.X) * -180 / Math.PI + 90);

                if (head < 0)
                    head = 360 + head;

                p.ShotHeading = head % 360;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog d = new Microsoft.Win32.SaveFileDialog();
            d.DefaultExt = ".rts";
            d.Filter = "Real-time script files|*.rts";

            var result = d.ShowDialog();

            if (result == true)
            {
                string fileName = d.FileName;
                string script = vm.BuildScript();

                System.IO.File.WriteAllText(fileName, script);
            }
        }
    }
}
